package com.atguigu.customer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.client.PaymentFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.OrderStatus;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;

@Component
public class OrderCustomer {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentFeignClient paymentFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //订单过了支付的时间 订单为关闭状态
    @RabbitListener(queues = MqConst.CANCEL_ORDER_QUEUE)
    public void cancelOrder(Long orderId, Message message, Channel channel) throws Exception {
        if (orderId != null){
            //根据订单id获取订单的信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            if (orderInfo != null && orderInfo.getOrderStatus().equals(OrderStatus.UNPAID.name())){
                //修改订单的状态为关闭
                orderInfoService.updateOrderStatus(orderInfo, ProcessStatus.CLOSED);
                //修改支付订单的状态为关闭
                PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                if (paymentInfo != null && paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
                    //为了解耦合  则给paymentInfo微服务 发送消息 进行修改支付状态为关闭
                    rabbitTemplate.convertAndSend(MqConst.CLOSE_PAYMENT_EXCHANGE,MqConst.CLOSE_PAYMENT_ROUTE_KEY,orderId);
                    //查看 支付宝是否创建了交易记录 有的话将支付宝那边交易关闭
                    boolean flag = paymentFeignClient.queryAlipayTrade(orderId);
                    if (flag){
                        //关闭支付宝的交易
                        paymentFeignClient.closeAlipayTrade(orderId);
                    }
                }
            }
        }
        //确认收到消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    //订单支付完成后 更改状态并发消息减库存
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.PAY_ORDER_QUEUE,durable = "false"),
    exchange = @Exchange(value = MqConst.PAY_ORDER_EXCHANGE,durable = "false"),
    key = {MqConst.PAY_ORDER_ROUTE_KEY}))
    public void updateOrderStatusAfterPay(Long orderId,Message message, Channel channel) throws Exception {
        if (orderId != null){
            OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
            //orderInfo不为空 且 订单状态为未支付的状态 再更改订单的状态
            if (orderInfo != null && orderInfo.getOrderStatus().equals(ProcessStatus.UNPAID.name())){
                orderInfo.setOrderStatus(OrderStatus.PAID.name());
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.PAID);

                //利用mq发送消息给库存系统 减库存
                orderInfoService.sendMsgToWareManage(orderInfo);
            }
        }
        //确认收到消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    //加完库存后 修改订单状态为待发货
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.SUCCESS_DECREASE_STOCK_QUEUE,durable = "false"),
    exchange = @Exchange(value = MqConst.SUCCESS_DECREASE_STOCK_EXCHANGE,durable = "false"),
    key = {MqConst.SUCCESS_DECREASE_STOCK_ROUTE_KEY}))
    public void updateOrderStatusAfterStock(String jsonStringFromStock,Message message, Channel channel) throws Exception {
        if (jsonStringFromStock != null){
            Map map = JSONObject.parseObject(jsonStringFromStock);
            String orderId = (String)map.get("orderId");
            String status = (String)map.get("status");
            OrderInfo orderInfo = orderInfoService.getOrderInfo(Long.parseLong(orderId));
            if ("DEDUCTED".equals(status)){
                //仓库系统发送的状态为DEDUCTED  说明减库存成功
                //在修改订单的状态为 待发货
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.WAITING_DELEVER);
            }else{
                //说明减库存失败 超卖了
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.STOCK_EXCEPTION);
            }
        }
        //确认收到消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
